<template>
  <div class="date-time-picker">
    <div class="date-range-section">
      <div class="range-options-container">
        <div
          class="range-option first-option"
          :class="{ 'range-option-active': currentRange === 'lastWeek' }"
          @click="handleRangeSelect('lastWeek')"
        >
          Last Week
        </div>
        <div
          class="range-option"
          :class="{ 'range-option-active': currentRange === 'lastMonth' }"
          @click="handleRangeSelect('lastMonth')"
        >
          Last Month
        </div>
        <div
          class="range-option"
          :class="{ 'range-option-active': currentRange === 'last3Months' }"
          @click="handleRangeSelect('last3Months')"
        >
          Last 3 Months
        </div>
        <div
          class="range-option last-option"
          :class="{ 'range-option-active': currentRange === 'thisYear' }"
          @click="handleRangeSelect('thisYear')"
        >
          This Year
        </div>
      </div>

      <div class="date-picker-group">
        <!-- <div class="date-range-label">Date Range</div> -->
        <div class="custom-date-container">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            align="right"
            unlink-panels
            format="dd/MM/yyyy"
            range-separator="—"
            start-placeholder="Start date"
            end-placeholder="End date"
            size="large"
            class="transparent-date-picker"
            @change="handleDateRangeChange"
          />
        </div>
      </div>
    </div>

    <div class="filter-section">
      <div class="frequency-filter">
        <!-- <div class="filter-label">Frequency</div> -->
        <div class="frequency-select">
          <el-select
            v-model="selectedFrequency"
            class="filter-select"
            @change="onFrequencyChange"
          >
            <el-option
              v-for="option in filteredFrequencyOpts"
              :key="option.value"
              :label="option.displayLabel"
              :value="option.value"
              size="small"
            />
          </el-select>
        </div>
      </div>
      <div class="refresh-btn">
        <img
          src="@/assets/refresh1.png"
          alt="Refresh"
          class="refresh-icon"
          @click="handleRefresh"
          :class="{ clicked: isRefreshing }"
          ref="refreshIcon"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { DatePicker, Select, Option } from "element-ui";
import lang from "element-ui/lib/locale/lang/en";
import locale from "element-ui/lib/locale";

// Configure Element UI to use English
locale.use(lang);

// 优化节流函数，添加操作频繁提示功能
const throttleWithTip = (fn, delay, tipText) => {
  let lastCall = 0;
  let isShowingTip = false; // 标记是否正在显示提示

  return function (...args) {
    const now = new Date().getTime();
    const elapsed = now - lastCall;

    if (elapsed < delay) {
      // 操作频繁时显示提示
      if (!isShowingTip) {
        isShowingTip = true;
        this.$message({
          message: tipText,
          type: "warning",
          duration: 2000, // 提示显示2秒
        });
        setTimeout(() => {
          isShowingTip = false;
        }, 2000);
      }
      return;
    }

    lastCall = now;
    fn.apply(this, args);
  };
};

const FREQUENCY_OPTIONS = [
  { value: "DAY", displayLabel: "Day" },
  { value: "WEEK", displayLabel: "Week" },
  { value: "MONTH", displayLabel: "Month" },
];

const FREQUENCY_MAP = {
  lastWeek: ["DAY"],
  lastMonth: ["WEEK"],
  last3Months: ["WEEK", "MONTH"],
  thisYear: ["MONTH", "WEEK"], // 仅添加这一行
};

export default {
  components: {
    [DatePicker.name]: DatePicker,
    [Select.name]: Select,
    [Option.name]: Option,
  },
  data() {
    return {
      allFrequencyOpts: FREQUENCY_OPTIONS,
      frequencyOptsMap: FREQUENCY_MAP,
      currentRange: "last3Months",
      selectedFrequency: "WEEK",
      dateRange: [],
      isCustomRange: false,
      today: new Date(),
      isRefreshing: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "Last week",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "Last month",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "Last 3 months",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate: this.disabledFutureDate,
        todayStyleInjected: false, // 标记样式是否已注入
      },
    };
  },
  computed: {
    filteredFrequencyOpts() {
      return this.isCustomRange
        ? this.allFrequencyOpts
        : this.allFrequencyOpts.filter((item) =>
            this.frequencyOptsMap[this.currentRange]?.includes(item.value)
          );
    },
  },
  mounted() {
    this.injectCalendarIcon();
    this.setDefaultDateRange();
    this.today.setHours(0, 0, 0, 0);
    this.$nextTick(this.handleRefresh);
  },
  methods: {
    disabledFutureDate(time) {
      return time > this.today;
    },
    setDefaultDateRange() {
      this.isCustomRange = false;
      const rangeMap = {
        lastMonth: this.getPreviousMonthRange(),
        lastWeek: this.getPreviousWeekRange(),
        last3Months: this.getPrevious3MonthsRange(),
        thisYear: this.getThisYearRange(), // 仅添加这一行
      };
      this.dateRange = rangeMap[this.currentRange] || [];
    },
    // 新增方法（与其他范围方法结构一致）
    getThisYearRange() {
      const end = new Date();
      const start = new Date(end.getFullYear(), 0, 1); // 今年1月1日
      return [start, end];
    },
    getPreviousWeekRange() {
      const end = new Date();
      const start = new Date(end.getTime() - 7 * 24 * 3600 * 1000);
      return [start, end];
    },
    getPreviousMonthRange() {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      this.adjustDateForMonthChange(start);
      return [start, end];
    },
    getPrevious3MonthsRange() {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      this.adjustDateForMonthChange(start);
      return [start, end];
    },
    adjustDateForMonthChange(date) {
      const day = date.getDate();
      const month = date.getMonth();
      const year = date.getFullYear();
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      date.setDate(Math.min(day, daysInMonth));
    },
    handleRangeSelect(range) {
      this.currentRange = range;
      this.selectedFrequency = "";
      this.setDefaultDateRange();
    },
    onFrequencyChange(value) {
      this.selectedFrequency = value;
    },
    handleDateRangeChange(range) {
      if (!range || range.length !== 2) return;

      if (range[1].getTime() > Date.now()) {
        this.$message.warning("The end date cannot exceed the current date");
        this.setDefaultDateRange();
        return;
      }

      this.isCustomRange = !this.isDateRangeInPreset(range);
      if (!this.isCustomRange) {
        this.setCurrentRangeForPreset(range);
      } else {
        this.currentRange = ""; // Clear current selected range
      }

      this.dateRange = range;
    },
    isDateRangeInPreset(range) {
      return (
        this.isSameRange(range, this.getPreviousWeekRange()) ||
        this.isSameRange(range, this.getPreviousMonthRange()) ||
        this.isSameRange(range, this.getPrevious3MonthsRange()) ||
        this.isSameRange(range, this.getThisYearRange()) // 仅添加这一行
      );
    },
    isSameRange(range1, range2) {
      return (
        range1?.length === 2 &&
        range2?.length === 2 &&
        range1[0].getTime() === range2[0].getTime() &&
        range1[1].getTime() === range2[1].getTime()
      );
    },
    setCurrentRangeForPreset(range) {
      const presetRanges = {
        lastWeek: this.getPreviousWeekRange(),
        lastMonth: this.getPreviousMonthRange(),
        last3Months: this.getPrevious3MonthsRange(),
        thisYear: this.getThisYearRange(), // 仅添加这一行
      };

      for (const [key, presetRange] of Object.entries(presetRanges)) {
        if (this.isSameRange(range, presetRange)) {
          this.currentRange = key;
          break;
        }
      }
    },
    handleRefresh: throttleWithTip(
      function () {
        const refreshIcon = this.$refs.refreshIcon;
        if (refreshIcon) {
          refreshIcon.classList.add("clicked");
          setTimeout(() => {
            refreshIcon.classList.remove("clicked");
          }, 200);
        }

        this.isRefreshing = true;
        this.$emit("date-change", {
          dateRange: this.dateRange,
          frequency: this.selectedFrequency,
        });

        setTimeout(() => {
          this.isRefreshing = false;
        }, 200);
      },
      3000,
      "Operation too frequent, please try again later."
    ),
    injectCalendarIcon() {
      const dateInput = document.querySelector(".el-date-editor");
      if (!dateInput) return;

      const iconEl = document.createElement("i");
      iconEl.classList.add("el-icon-date");
      Object.assign(iconEl.style, {
        position: "absolute",
        top: "11px",
        right: "20px",
      });
      dateInput.appendChild(iconEl);
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box; // 所有元素默认使用border-box，避免padding/border撑开高度
}
.date-time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  // height: 0.4444rem;
  // margin-top: 20px;
  padding: 10px 0;
  border: 1px solid #cdcccc;
  border-radius: 8px;
  background: #fff;
  // box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

.date-range-section {
  display: flex;
  align-items: center;
  gap: 16px;
  .range-options-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .date-picker-group {
    width: 1.7292rem;
    // height: 40px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px solid #6a6969;
    border-radius: 0.0278rem;
    // padding: 4px 0 0;
  }
}

.range-option {
  padding: 10px 16px;
  font-size: 0.0972rem;
  font-weight: 400;
  color: #232323;
  cursor: pointer;
  // border-radius: 0.0278rem;
  transition: all 0.3s ease;
  // border-right: 1px solid #6a6969;
  // border-top: 1px solid #6a6969;
  // border-bottom: 1px solid #6a6969;

  &.range-option-active {
    background-color: #4485e9;
    color: #fff;
    font-size: 0.0972rem;
    border-radius: 4px;
    // font-weight: 600;
  }
  // 第一个选项：不需要左侧边框（由外层容器提供）
  &.first-option {
    // border-left: 1px solid #6a6969; /* 外层容器已有左侧边框，避免重复 */
    // border-top-left-radius: 4px;

    // border-bottom-left-radius: 4px;
  }
  &.last-option {
    // border-left: 1px solid #6a6969; /* 外层容器已有左侧边框，避免重复 */
    // border-top-right-radius: 4px;
    // border-bottom-right-radius: 4px;
  }
}

.date-range-label {
  // padding: 0 14px;
  font-size: 10px;
  font-weight: 400;
  color: #8f8f8f;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 16px;

  .frequency-filter {
    border: 1px solid #6a6969;
    width: 1.0417rem;

    border-radius: 0.0278rem;
    padding: 0px 15px;
    box-sizing: border-box;
  }
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.frequency-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 36px;
  padding: 4px 0;
}

.refresh-btn {
  width: .2222rem;
  height: .2222rem;
  margin-left: 16px;
  display: flex;
  align-items: center;

  .refresh-icon {
    width: 100%;
    height: 100%;
    cursor: pointer;
    padding: 2px;
    box-sizing: border-box;
    border: 2px solid transparent;
    transition: all 0.2s ease;

    &:hover {
      opacity: 0.8;
    }

    &.clicked {
      // border-color: #0d4c80;
      // border-radius: 2px;
      // padding: 0;
    }
  }
}

::v-deep.el-date-editor .el-range-separator {
  line-height: 20px;
  padding: 0;
  // font-size: .0972rem;
}

.custom-date-container {
  ::v-deep .el-input__inner {
    box-sizing: bor;

    border-radius: 8px;
    width: 1.7292rem;
    height: auto;
    display: flex;
    align-items: center;
    text-align: center;
    padding: 8px 0;
  }

  ::v-deep.el-input__suffix {
    right: -90px;
    color: #000 !important;
  }

  .frequency-filter {
    ::v-deep .el-select {
      width: 100% !important;
      font-family: "Inter Variable", sans-serif;
    }
  }

  ::v-deep .el-range__icon {
    display: none;
  }
}

::v-deep .el-input__inner {
  background-color: transparent !important;
  height: 0.1389rem;
  // padding: 12px 0px;
  color: #232323 !important;
  border: none;
}

.date-time-picker .custom-date-container ::v-deep .el-input__inner {
  color: #000 !important;
}

::v-deep.el-date-editor .el-range-input {
  font-size: 0.0972rem;
  color: #000 !important;
  background-color: transparent; /* 透明背景，继承容器背景 */
  border: none; /* 去掉输入框自身边框（如果不需要） */
}

::v-deep .el-select .el-input .el-select__caret {
  color: #6a6a6a;
  font-weight: 400;
}

::v-deep .el-select .el-input__inner {
  font-family: "Inter Variable", sans-serif;
  font-size: 0.0972rem !important;
  color: red;
  padding: 10px 0; // 与日历输入框padding一致
  height: auto; // 由padding撑开高度
}
::v-deep .el-select .el-select-dropdown__item {
  font-family: "Inter Variable", sans-serif;
  font-size: 0.0972rem !important;
  color: red;
}
// 彻底隐藏日期范围选择器的清除图标（×）
::v-deep .el-date-editor .el-range__close-icon {
  display: none !important;
}
</style>
